package com.qingfeng.manager.config.shiro;

import com.qingfeng.core.entity.Permission;
import com.qingfeng.core.entity.Role;
import com.qingfeng.core.entity.Userinfo;
import com.qingfeng.manager.service.PermissionService;
import com.qingfeng.manager.service.RoleService;
import com.qingfeng.manager.service.UserinfoService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author:LWY
 * @date: 2017/10/16 15:29
 * @modified:
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    UserinfoService userinfoService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService PermissionService;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        System.out.println(authenticationToken.getCredentials());
        //获取用户的输入的账号.
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());
        Userinfo userInfo = userinfoService.getUser(username, password);
        System.out.println("----->>userInfo=" + userInfo);
        if (userInfo == null) {
            throw new AccountException("帐号或密码不正确！");
        } else if (userInfo.getState() == 0) {
            throw new DisabledAccountException("此帐号已经设置为禁止登录！");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo,//用户名
                password, //密码
                getName()  //realm name
        );
        return authenticationInfo;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Userinfo userInfo = (Userinfo) principalCollection.getPrimaryPrincipal();
        List<Role> roles = roleService.byUserinfo(userInfo.getId());
        for (Role role : roles) {
            authorizationInfo.addRole(role.getId());
            Set<Permission> permisions = PermissionService.byRole(role.getId());
            for (Permission p : permisions) {
                authorizationInfo.addStringPermission(p.getId());
            }
        }
        return authorizationInfo;
    }
}
